<?php

declare(strict_types=1);

namespace App\Middleware;

use App\Constants\ErrorCode;
use App\Constants\StatusCode;
use App\Exception\Handler\AppException;

use App\Exception\Handler\BusinessException;
use App\Foundation\Traits\CryptTrait;
use App\Service\Auth\UserService;
use App\Model\Auth\Role;
use http\Exception\BadConversionException;
use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;
use Hyperf\HttpServer\Router\Dispatched;
use Hyperf\Utils\Context;
use Phper666\JWTAuth\JWT;
use PhpParser\Node\Expr\New_;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;


class DecryptMiddleware implements MiddlewareInterface
{

    use CryptTrait;


    protected $container;


    protected $request;


    protected $response;


    public function __construct(ContainerInterface $container, HttpResponse $response, RequestInterface $request)
    {
        $this->container = $container;
        $this->response = $response;
        $this->request = $request;
    }


    /**
     * 权限校验中间件
     * @param ServerRequestInterface $request
     * @param RequestHandlerInterface $handler
     * @return ResponseInterface
     */
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {

        $appId = $this->request->input("app_id");


        if (empty($appId)){
            Throw new BusinessException(ErrorCode::APP_ERR);
        }

        $apps = Db::table('app')->where("id",$appId)->first();

        if (!$apps->status || $apps->status==3){
           // Throw new BusinessException(ErrorCode::APP_ERR);
        }

        $data = $this->getDecryptData($appId,$this->request);


        if ($data==ErrorCode::DECRPYPT_ERR){
            Throw new BusinessException(ErrorCode::APP_ERR);
        }

        $request = Context::override(ServerRequestInterface::class, function (ServerRequestInterface $request) use($data) {
            return $request->withAttribute("descrypt_data",$data);
        });

        return $handler->handle($request);
    }
}
